package ru.spies.help;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Collection;

import ru.spies.content.SystemContent;
import ru.spies.dbwork.DBQueries;
import ru.spies.dbwork.DBWork;
import ru.spies.entities.Siteuser;
import ru.spies.profileClasses.RoleInfo;
import ru.spies.profileClasses.UserInfo;
import ru.spies.work.ShowResults;

public class DataTableCreator {

	private static DataTableCreator statThis;
	
	private static final String NOTHING="Отсутствует";
	
	private String tableName=null;
	private String columns[]=null;

	private DataTableCreator() {
		
	}
	
	public static DataTableCreator getInstance(String tableName){
		if (statThis==null){
			statThis = new DataTableCreator();
		}
		statThis.setTableName(tableName);
		return statThis;
	}
	
	public String getJSSource(String columns[]){
		statThis.setColumns(columns);
		return "<script src=\"spiesSite.js\"> </script><script src=\"jquery.js\"></script><script src=\"jquery.dataTables.js\"></script><script>"+createJSWithDataTable()+"</script>";
	}
	
	private String createJSWithDataTable(){
		return SystemContent.getInstance().jsFileForDataTableContent(tableName, tableName, columns);
	}
	
	private void setTableName(String tableName){
		this.tableName=tableName;
	}
	
	private void setColumns(String columns[]){
		this.columns=columns;
	}

	public String getTableRow(String colName[], String colValue[]){
		StringBuffer row = new StringBuffer("{");
		for (int i = 0; i < colName.length-1; i++) {
			row.append(" \"");
			row.append(colName[i]);
			row.append("\" : \"");
			if (colValue[i]!=null){
				row.append(colValue[i]);
			} else {
				row.append(NOTHING);
			}		
			row.append("\", ");
		}
		row.append(" \"");
		row.append(colName[colName.length-1]);
		row.append("\" : \"");
		if (colValue[colValue.length-1]!=null){
			row.append(colValue[colValue.length-1]);
		} else {
			row.append(NOTHING);
		}	
		row.append("\" },");
		return row.toString();
	}
	
	public void wrapTable(String text){
		createFileForDataTable(getWrapper(new StringBuffer(text),true).toString());
	}
	
	public void fillUsersTable(){
		StringBuffer dataTableFileContent = new StringBuffer();	
		Collection<Siteuser> countries =  (Collection<Siteuser>) DBWork.getInstance().getTableObjects(DBQueries.QUERY_SITEUSERS_FIND);
		for (Siteuser i:countries){
			dataTableFileContent.append("{ \"userName\" : \"");
			dataTableFileContent.append(i.getUsername());
			dataTableFileContent.append("\", \"role\" : \"");
			dataTableFileContent.append(RoleInfo.getTrueRole(i.getRole().getName()));
			if (UserInfo.getInstance().getPrivileges().canDoNormalShow()){
				dataTableFileContent.append("\", \"agentName\" : \"");
				dataTableFileContent.append(i.getAgent().getName());
			}
			dataTableFileContent.append("\"},");
		}
		if (dataTableFileContent.length()>16){
			dataTableFileContent.replace(dataTableFileContent.lastIndexOf(","), dataTableFileContent.length(), "");
		} else {
			dataTableFileContent.append("{ \"userName\" : \""+NOTHING+" \", \"role\" : \""+NOTHING+" \"");
			if (UserInfo.getInstance().getPrivileges().canDoNormalShow()){
				dataTableFileContent.append(", \"agentName\" : \""+NOTHING+"\"");
			}
			dataTableFileContent.append("}");
		}
		dataTableFileContent=getWrapper(dataTableFileContent,false);
		createFileForDataTable(dataTableFileContent.toString());
	}
	
	private void createFileForDataTable(String text){
		String fileName = ShowResults.getInstance().getMainPath()+tableName+".txt";
		File f = new File(fileName);
		if (f.exists()){
			f.delete();
		}
		try {
			f.createNewFile();
		} catch (IOException e) {
			MyLogger.getInstance().getLog().error(MyLogger.EXCEPTION,e);
		}
		Writer out;
		try {
			out = new OutputStreamWriter(new FileOutputStream(f),"UTF-8");
			out.write(text);
			out.close();
		} catch (IOException e) {
			MyLogger.getInstance().getLog().error(MyLogger.EXCEPTION,e);
		}
	}
	
	private StringBuffer getWrapper(StringBuffer textToWrap,boolean needToDelLastSeparator){
		if (needToDelLastSeparator){
			textToWrap=textToWrap.replace(textToWrap.lastIndexOf(","),textToWrap.lastIndexOf(",")+1, " ");
		}
		StringBuffer wrapper = new StringBuffer("{ \"aaData\": [ ");
		wrapper.append(textToWrap);
		wrapper.append(" ] }");
		return wrapper;
	}

}
